﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZXing;  //引用命名空间
using ZXing.QrCode;

namespace MyTest
{
    /// <summary>
    /// 教员:薛海
    /// 微信:xuehai03
    /// QQ:289477003
    /// 条形码
    /// 2019-2-20
    /// </summary>
    public partial class FrmZXing : Form
    {
        public FrmZXing()
        {
            InitializeComponent();
        }



        //生成二维码的方法
        public Bitmap getImg(string msg)
        {
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            //设置字符编码
            writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "utf-8");
            writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, 
               ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            //设置二维码大小
            const int codeSize = 140;
            writer.Options.Height = writer.Options.Width = codeSize;
            //设置二维码边距
            writer.Options.Margin = 1;
            ZXing.Common.BitMatrix bm = writer.Encode(msg);
            //生成二维码图片
            Bitmap img = writer.Write(bm);
            //显示到图片框中
            this.pictureBox1.Image = img;
            return img;
        }

        //点击事件
        private void button1_Click(object sender, EventArgs e)
        {
            //随机数对象
            Random ran = new Random();
            //生成6位随机数
            string num = ran.Next(1, 1000000).ToString();
            //调用方法
            this.getImg(num);
            //显示随机数到文本框
            this.textBox1.Text = num;
        }

        //生成条形码
        public void Generate(string text)
        {
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.CODE_128;

            //设置大小和边距
            QrCodeEncodingOptions options = new QrCodeEncodingOptions()
            {
                Width = 150,
                Height = 50,
                Margin = 2
            };
            writer.Options = options;
            //生成条形码
            Bitmap map = writer.Write(text);
            //显示到图片框中
            this.pictureBox1.Image = map;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Random ran = new Random();
            this.Generate(ran.Next().ToString());
        }
    }
}
